package com.dhcc.bpm.modules.mail.service.impl;

import com.dhcc.bpm.modules.mail.service.SendEasternMsgService;
import com.dhcc.bpm.modules.mail.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@Component
public class SendEasternMsgServiceImpl implements SendEasternMsgService {

    @Value("${ceair.msg.ceair-mail-key}")
    private String mailKey;

    @Value("${ceair.msg.ceair-mail-biz-product}")
    private String mailBizProduct;

    @Value("${ceair.msg.ceair-wechat-key}")
    private String wechatKey;

    @Value("${ceair.msg.ceair-wechat-biz-product}")
    private String wechatBizProduct;

    @Value("${ceair.msg.ceair-sms-key}")
    private String smsKey;

    @Value("${ceair.msg.ceair-sms-biz-product}")
    private String smsBizProduct;

    @Value("${ceair.msg.ceair-end-point}")
    private String endPoint;

    @Value("${ceair.msg.ceair-from-user-id}")
    private String fromUserId;

    private static URL wsdlURL;

    //后期切换使用SOA平台使用，添加请求头信息
    @Autowired
    private HeaderHandlerResolver headerHandlerResolver;


    @PostConstruct
    public void init() throws MalformedURLException {

        wsdlURL = new URL(endPoint);

    }

    /**
     * 推送消息
     * @param batch
     * @return boolean
     */
    private String sendMsg(MessageRequestBatchVO batch) {
        try {
            log.info(batch.getMessageRequests().get(0).toString());
            MessageRequestResult messageRequestResult = getConnection().sendBatch(batch);
            if (messageRequestResult.isSuccess()) {
                return messageRequestResult.getData();
            } else {
                log.error("发送消息异常:{}",
                        messageRequestResult.getResultCode() + "(" + messageRequestResult.getDesc() + "),data:"
                        +messageRequestResult.getData());
                return null;
            }
        } catch (Exception e) {
            log.error("" ,  e.getMessage());
            return null;
        }
    }

    /**
     * 推送微信
     * @param title
     * @param content
     * @param userList
     * @return boolean
     */
    @Override
    public String sendWeChat(String title, String content, List<String> userList) {
        return msgBuild(title,content,userList,MuSendMsgType.WeChat.name());
    }

    /**
     * 推送短信
     * @param title
     * @param content
     * @param userList
     * @return boolean
     */
    @Override
    public String sendSms(String title, String content, List<String> userList) {
        return msgBuild(title,content,userList,MuSendMsgType.Sms.name());
    }

    /**
     * 推送邮件
     * @param title
     * @param content
     * @param userList
     * @return boolean
     */
    @Override
    public String sendMail(String title, String content, List<String> userList) {
        return msgBuild(title,content,userList, MuSendMsgType.Mail.name());
    }

    /**
     * 获取链接
     * @return
     * @throws Exception
     */
    private MessageEndpoint getConnection() throws Exception {
        MessageEndpoint_Service service = new MessageEndpoint_Service(wsdlURL);
        //添加请求头信息，后期切换是用SOA平台使用
//        service.setHandlerResolver(headerHandlerResolver);
        return service.getMessageEndpointImplPort();
    }

    /**
     * 创建发送消息
     * @param title
     * @param content
     * @param userList
     * @param type
     * @return boolean
     */
    private String msgBuild(String title, String content, List<String> userList, String type) {
        MessageRequestBatchVO batch = new MessageRequestBatchVO();
        for (String userId : userList) {
            MessageRequestVO messageRequestVO = new MessageRequestVO();
            messageRequestVO.setRequestId(UUID.randomUUID().toString());
            messageRequestVO.setTitle(title);
            messageRequestVO.setContent(content);
            messageRequestVO.setFromUserId(fromUserId);
            if (type.equals(MuSendMsgType.WeChat.name())) {
                messageRequestVO.setBizProduct(wechatBizProduct);
                messageRequestVO.setPrivateKey(wechatKey);
                messageRequestVO.setToUserId(userId);
            } else if (type.equals(MuSendMsgType.Sms.name())) {
                messageRequestVO.setBizProduct(smsBizProduct);
                messageRequestVO.setPrivateKey(smsKey);
                messageRequestVO.setToMobile(userId);
            } else {
                messageRequestVO.setBizProduct(mailBizProduct);
                messageRequestVO.setPrivateKey(mailKey);
                messageRequestVO.setToMail(userId);
            }
            batch.getMessageRequests().add(messageRequestVO);
        }
        if (batch.getMessageRequests().size() > 0) {
            return sendMsg(batch);
        }
        log.error("SendMessageService ceair msg error:",  "发送消息异常");
        return null;
    }
}
